#运行前输入pip install matplotlib control安装matplotlib库和control库
import numpy as np
import matplotlib.pyplot as plt
from control import tf, rlocus, margin

# 定义传递函数
# 例如，定义一个典型的二阶系统 G(s) = 1 / (s^2 + 2s + 1)
num = [1]  # 分子多项式系数
den = [1, 2, 1]  # 分母多项式系数

# 创建传递函数对象
system = tf(num, den)

# 绘制根轨迹图
plt.figure()
rlocus(system, Plot=True)
plt.title('Root Locus of the System')
plt.grid(True)
plt.show()

# 计算增益裕度、相位裕度等
gain_margin, phase_margin, gain_cross_freq, phase_cross_freq = margin(system)

print("Gain Margin (dB):", gain_margin)
print("Phase Margin (degrees):", phase_margin)
print("Gain Crossover Frequency (rad/s):", gain_cross_freq)
print("Phase Crossover Frequency (rad/s):", phase_cross_freq)

# 判断稳定性
if gain_margin > 0 and phase_margin > 0:
    print("The system is stable with the given gain and phase margins.")
else:
    print("The system is unstable with the given gain and phase margins.")
